<?php


namespace api\crm\controller;


use api\crm\model\CartModel;
use api\crm\model\GoodsModel;
use api\crm\model\GoodsSpecModel;
use api\crm\model\OrderGoodsModel;
use api\crm\model\OrderInfoModel;
use api\crm\model\UserModel;
use api\crm\model\WechatUserAddressModel;
use api\crm\model\WechatUserModel;
use api\crm\model\WechatUserPointsLogModel;
use app\admin\model\CategoryModel;
use app\admin\model\GetCardLogModel;
use cmf\controller\RestBaseController;
use plugins\wechat\WechatPlugin;
use think\Db;
use think\Exception;

class GoodsController extends RestBaseController
{
    public function get_goods_list()
    {
        $data = $this->request->param();
        $num = 10;
        $page = isset($data['page']) && $data['page'] ? intval($data['page']) : 1;
        $company_id = isset($data['company_id']) && $data['company_id'] ? $data['company_id'] : 0;
        $where[] = ['company_id', '=', $company_id];
        $where[] = ['is_on_sale', '=', 1];
        $where[] = ['is_delete', '=', 0];
        $category_id = isset($data['category_id']) && $data['category_id'] ? $data['category_id'] : 0;
        if ($category_id) {
            $where[] = ['cate_id', '=', $category_id];
        }
        $keyword = isset($data['keyword']) && $data['keyword'] ? $data['keyword'] : 0;
        if ($keyword) {
            $where[] = ['goods_name', 'like', '%' . $keyword . '%'];
        }
        $goods_list = GoodsModel::with('category_info')->where($where)
            ->order('sort desc,create_time desc')
            ->paginate($num, false, ['page' => $page])->each(function ($item) {
                if ($item['goods_img']) {
                    $array = explode(',', $item['goods_img']);
                    $temp_array = [];
                    foreach ($array as $value) {
                        $temp_array[] = $this->request->domain() . $value;
                    }
                    $item['goods_img'] = $temp_array;
                }
                return $item;
            });
        $this->success('获取商品列表', $goods_list);
    }

    public function get_goods_by_id()
    {
        $data = $this->request->param();
        $id = isset($data['id']) && $data['id'] ? intval($data['id']) : 0;
        $goods_info = GoodsModel::with('goods_specs')->where(['id' => $id, 'is_delete' => 0, 'is_on_sale' => 1])->find();
        if (empty($goods_info)) {
            $this->error('商品不存在或下架');
        }
        $openid = isset($data['openid']) && $data['openid'] ? $data['openid'] : '';
        if ($openid) {
            $user_id = $this->getWechatUserId();
            $cart_num = CartModel::where(['user_id' => $user_id, 'status' => 0])->sum('num');
            $goods_info['cart_num'] = $cart_num;
            $goods_info['user_points'] = WechatUserModel::where('id', $user_id)->value('points');
        }
        if ($goods_info['goods_img']) {
            $array = explode(',', $goods_info['goods_img']);
            $temp_array = [];
            foreach ($array as $value) {
                $temp_array[] = $this->request->domain() . $value;
            }
            $goods_info['goods_detail'] = preg_replace_callback('/<[img|IMG].*?src=[\'| \"](?![http|https])(.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/', function ($r) {
                $str = $this->request->domain() . $r[1];
                return str_replace($r[1], $str, $r[0]);
            }, $goods_info['goods_detail']);
            $goods_info['goods_img'] = $temp_array;
        }
        $this->success('获取商品详细', $goods_info);
    }

    public function get_category_list()
    {
        $data = $this->request->param();
        $company_id = isset($data['company_id']) && $data['company_id'] ? $data['company_id'] : 0;
        if (empty($company_id)) {
            $this->error('请传入公司id');
        }
        $list = CategoryModel::where('company_id', $company_id)
            ->where('status', 1)
            ->order('sort desc')->all();
        $this->success('获取分类列表', $list);
    }

    public function add_cart()
    {
        try {
            Db::startTrans();
            $data = $this->request->param();
            $goods_id = isset($data['goods_id']) && $data['goods_id'] ? $data['goods_id'] : 0;
            $num = isset($data['num']) && $data['num'] ? intval($data['num']) : 0;
            $spec_id = isset($data['spec_id']) && $data['spec_id'] ? $data['spec_id'] : 0;
            $goods_info = GoodsModel::with('goods_specs')->where(['is_on_sale' => 1, 'is_delete' => 0])->get($goods_id);
            if (empty($goods_info)) {
                throw new Exception('商品不存在或已删除');
            }
            $spec_info = GoodsSpecModel::where(['goods_id' => $goods_id, 'id' => $spec_id])->find();
            if (empty($spec_info)) {
                if ($goods_info['stock'] <= 0) {
                    throw new Exception('商品库存不足');
                }

                if (count($goods_info['goods_specs']) > 0) {
                    throw new Exception('请选择规格');
                }
                $unit_price = $goods_info['price'];
                $goods_points = $goods_info['points'];
            } else {
                if ($spec_info['stock'] <= 0) {
                    throw new Exception('商品库存不足');
                }
                $unit_price = $spec_info['price'];
                $goods_points = $spec_info['points'];
            }
            if ($num <= 0) {
                throw new Exception('购买商品数不能为0');
            }
            $user_id = $this->getWechatUserId();
            $cart_model = CartModel::where(['goods_id' => $goods_id, 'user_id' => $user_id, 'status' => 0, 'spec_id' => $spec_id])->find();

            if (empty($cart_model)) {
                $cart_model = new  CartModel();
                $cart_model->goods_id = $goods_id;
                $cart_model->user_id = $user_id;

                $goods_info->stock = ['dec', $num];
                if ($spec_info) {
                    $spec_info->stock = ['dec', $num];
                    $spec_info->save();
                }
                $goods_info->save();
            } else {
                $type = isset($data['type']) && $data['type'] ? $data['type'] : '';
                $current_num = $cart_model['num'];
                switch ($type) {
                    case 'inc':
                        $goods_info->stock = ['dec', $num];
                        if ($spec_info) {
                            $spec_info->stock = ['dec', $num];
                            $spec_info->save();
                        }
                        $goods_info->save();
                        $num = $num + $current_num;
                        break;
                    case 'dec':
                        $goods_info->stock = ['inc', $num];
                        if ($spec_info) {
                            $spec_info->stock = ['inc', $num];
                            $spec_info->save();
                        }
                        $goods_info->save();
                        $num = $current_num - $num;
                        if ($num == 0) {
                            $num = 1;
                        }
                        break;
                }
            }
            $cart_model->num = $num;
            if ($goods_info['buy_type'] != 1) {
                $cart_model->goods_price = $unit_price;
                $cart_model->order_price = $unit_price * $num;
            }
            $cart_model->gift_points = $goods_info['gift_points'] * $num;
            if ($goods_info['buy_type'] >= 1) {
                $cart_model->points = $goods_points * $num;
            }
            $cart_model->spec_id = $spec_id;
            $res = $cart_model->save();
            if ($res) {
                Db::commit();
                $this->success('修改成功');
            } else {
                throw new Exception('添加购物车失败');
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    public function get_user_cart()
    {
        $user_id = $this->getWechatUserId();
        $list = CartModel::with(['goods_spec_info'])
            ->order('create_time desc')
            ->where(['user_id' => $user_id, 'status' => 0])->select()->each(function ($item) {
                $goods_info = GoodsModel::get($item['goods_id']);
                if ($goods_info['goods_img']) {
                    $array = explode(',', $goods_info['goods_img']);
                    $temp = [];
                    foreach ($array as $img) {
                        $temp[] = $this->request->domain() . $img;
                    }
                    $goods_info['goods_img'] = $temp;
                    $item['goods_info'] = $goods_info;
                }
                return $item;
            });
        $this->success('获取我的购物车', $list);
    }

    public function confirm_order()
    {
        try {
            Db::startTrans();
            $data = $this->request->param();
            $user_id = $this->getWechatUserId();
            $cart_ids = isset($data['card_ids']) && $data['card_ids'] ? $data['card_ids'] : '';
            $goods_id = isset($data['goods_id']) && $data['goods_id'] ? $data['goods_id'] : '';
            $user_info = WechatUserModel::get($user_id);
            //购物车
            $order_price = 0;
            $pay_points = 0;
            $gift_points = 0;
            $num = 0;
            $goods_list = [];
            if ($cart_ids) {
                $cart_info = CartModel::where('user_id', $user_id)->where('id', 'in', $cart_ids)
                    ->where('status', 0)
                    ->select();
                foreach ($cart_info as $key => $value) {
                    $goods_info = GoodsModel::get($value['goods_id']);
                    $goods_info['buy_num'] = $value['num'];
                    $goods_info['goods_price'] = $value['goods_price'];
                    $order_price += $value['order_price'];
                    $pay_points += $value['points'];
                    $gift_points += $value['gift_points'] * $value['num'];
                    $num += $value['num'];
                    $goods_info['spec_id'] = $value['spec_id'];
                    $goods_info['points'] = $value['points'];
                    $goods_list[] = $goods_info;
                }
                CartModel::where('user_id', $user_id)
                    ->where('id', 'in', $cart_ids)
                    ->update(['status' => 1]);
            }
            //直接购买
            if ($goods_id) {
                $goods_info = GoodsModel::with(['goods_specs'])->get($goods_id);
                $num = isset($data['num']) && $data['num'] ? $data['num'] : 1;
                $goods_price = $goods_info['price'];
                $need_pay_points = 0;
                $spec_id = isset($data['spec_id']) && $data['spec_id'] ? $data['spec_id'] : 0;
                if ($goods_info['buy_type'] >= 1) {
                    $need_pay_points = $goods_info['points'];
                }
                if (count($goods_info['goods_specs']) > 0) {
                    $spec_info = GoodsSpecModel::get($spec_id);
                    if (empty($spec_info)) {
                        throw new Exception('请选择商品规格');
                    }
                    if ($goods_info['buy_type'] >= 1) {
                        $need_pay_points = $spec_info['points'];
                    }
                    $goods_info['spec_id'] = $spec_id;
                    $goods_price = $spec_info['price'];
                    if ($num > $spec_info['stock']) {
                        throw new Exception('商品库存不足');
                    }
                    $spec_info->stock = ['dec', $num];
                    $spec_info->save();
                } else {
                    if ($num > $goods_info['stock']) {
                        throw new Exception('商品库存不足');
                    }

                }
                $goods_info->stock = ['dec', $num];
                $goods_info->save();
                if ($goods_info['buy_type'] != 1) {
                    $goods_info['goods_price'] = $goods_price;
                    $order_price = $goods_price * $num;
                } else {
                    $goods_info['goods_price'] = 0;
                }

                $gift_points += $goods_info['gift_points'] * $num;
                $goods_info['buy_num'] = $num;
                if ($need_pay_points >= 0) {
                    $pay_points = $need_pay_points * $num;
                }
                $goods_list[] = $goods_info;
            }
            $order = new OrderInfoModel();
            $order->order_sn = 'GOODS_' . cmf_get_order_sn();
            $order->company_id = $user_info['company_id'];
            $order->user_id = $user_id;
            $order->order_price = $order_price;
            $order->real_price = $order_price;
            $order->pay_points = $pay_points;
            $order->gift_points = $gift_points;
            $order->num = $num;
            $res = $order->save();
            if ($res) {
                $order_goods_model = new OrderGoodsModel();
                $list = [];
                foreach ($goods_list as $key => $value) {
                    $list[$key]['order_id'] = $order->id;
                    $list[$key]['goods_id'] = $value['id'];
                    $list[$key]['goods_name'] = $value['goods_name'];
                    $list[$key]['goods_price'] = $value['goods_price'];
                    if ($value['buy_type'] >= 1) {
                        $list[$key]['points'] = $value['points'];
                    } else {
                        $list[$key]['points'] = 0;
                    }
                    $list[$key]['num'] = $value['buy_num'];
                    $list[$key]['total_price'] = $value['goods_price'] * $value['buy_num'];
                    $list[$key]['gift_points'] = $value['gift_points'] * $value['buy_num'];
                    $list[$key]['spec_id'] = isset($value['spec_id']) && $value['spec_id'] ? $value['spec_id'] : 0;
                }
                if (empty($list)) {
                    throw new Exception('订单商品数据异常');
                }
                $order_goods_model->saveAll($list);
                Db::commit();
                $order_info = OrderInfoModel::with(['order_goods_list' => ['goods_img', 'goods_spec']])
                    ->get($order->id);
                $order_goods_list = $order_info['order_goods_list'];
                foreach ($order_goods_list as $key => $value) {
                    $img = $value['img'];
                    if ($img) {
                        $temp_array = [];
                        $array = explode(',', $img);
                        foreach ($array as $img_url) {
                            $temp_array[] = $this->request->domain() . $img_url;
                        }
                        $order_goods_list[$key]['img'] = $temp_array;
                    }
                }
                $order_info['order_goods_list'] = $order_goods_list;
                $this->success('确认订单成功', ['order_info' => $order_info]);
            } else {
                throw new Exception('确认订单失败');
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    public function pay_order()
    {
        try {
            Db::startTrans();
            $data = $this->request->param();
            $user_id = $this->getWechatUserId();
            $user_info = WechatUserModel::get($user_id);
            $order_sn = isset($data['order_sn']) && $data['order_sn'] ? $data['order_sn'] : '';
            $order_info = OrderInfoModel::where(['order_sn' => $order_sn,
                'order_status' => 0,
                'pay_status' => 0, 'user_id' => $user_id])->find();
            if (empty($order_info)) {
                throw new Exception('订单数据异常');
            }
            if ($user_info['points'] < $order_info['pay_points']) {
                throw new Exception('用户积分不足');
            }
            $address_id = isset($data['address_id']) && $data['address_id'] ? $data['address_id'] : 0;
            $address_info = WechatUserAddressModel::get($address_id);
            if (empty($address_info)) {
                throw new Exception('选择的地址不存在或被删除');
            }
            $card_id = isset($data['card_id']) && $data['card_id'] ? $data['card_id'] : '';
            $coupon_money = isset($data['coupon_money']) && $data['coupon_money'] ? $data['coupon_money'] : 0;
            $real_price = $order_info['real_price'] - $coupon_money;
            if ($card_id) {
                $card_info = GetCardLogModel::where('openid', $user_info['openid'])->get($card_id);
                $card_param['company_id'] = $order_info['company_id'];
                $card_param['card_id'] = $card_info['card_id'];
                $card_param['code'] = $card_info['user_card_code'];
                $card_status = hook('check_card_status', $card_param);
                if ($card_status[0]['errcode'] == 0) {
                    if ($card_status[0]['can_consume'] == false) {
                        throw new Exception('卡券已被使用');
                    }
                } else {
                    throw new Exception('获取卡券状态异常');
                }
                $order_info->card_id = $card_info['card_id'];
                $order_info->card_code = $card_info['user_card_code'];

            }
            $pay_sn = "PAY_" . cmf_get_order_sn();
            $order_info->remark = isset($data['remark']) && $data['remark'] ? $data['remark'] : '';
            $order_info->consignee = $address_info['name'];
            $order_info->mobile = $address_info['mobile'];
            $order_info->province = $address_info['province'];
            $order_info->city = $address_info['city'];
            $order_info->area = $address_info['area'];
            $order_info->address = $address_info['address'];
            $order_info->real_price = $real_price;
            $order_info->coupon_money = $coupon_money;
            $order_info->pay_sn = $pay_sn;
            if ($real_price == 0) {
                if ($card_id) {
                    $card_info = GetCardLogModel::where('openid', $user_info['openid'])->get($card_id);
                    $param['company_id'] = $order_info['company_id'];
                    $param['code'] = $order_info['card_code'];
                    hook('consume_coupon', $param);
                    $card_info->status = 1;
                    $card_info->save();
                }
                if ($order_info['pay_points'] > 0) {
                    //支付积分
                    $user_points = $user_info['points'];
                    $pay_points = $order_info['pay_points'];
                    $order_info->pay_status = 2;
                    $order_info->pay_time = time();
                    $res = $order_info->save();
                    if ($res) {
                        $log = new WechatUserPointsLogModel([
                            'user_id' => $user_id,
                            'change_points' => $pay_points,
                            'before_points' => $user_points,
                            'after_points' => $user_points - $pay_points,
                            'order_sn' => $order_sn,
                            'remark' => '订单号' . $order_sn . '消耗' . $pay_points . '积分'
                        ]);
                        $log->save();
                        $user_info->points = ['dec', $pay_points];
                        $user_info->save();

                        // 变更 会员卡 积分
                        $obj = new WechatPlugin();

                        $obj->update_card_info([
                            'company_id' => $user_info['company_id'],
                            'user_id'    => $user_info['id'],
                            'cardId'     => $card_info['card_id'],
                            'code'       => $card_info['user_card_code'],
                            'bonus'      => $user_points - $pay_points,
                        ]);

                        Db::commit();
                        $this->success('购买成功');
                    }
                } else {
                    $order_info->pay_status = 2;
                    $order_info->pay_time = time();
                    $res = $order_info->save();
                    if ($res) {
                        Db::commit();
                        $this->success('购买成功');
                    }
                }
            } else {
                $order_info->pay_status = 1;
                $res = $order_info->save();

                $params['company_id'] = $order_info['company_id'];
                $params['url'] = isset($data['url']) && $data['url'] ? $data['url'] : '';
                $params['openid'] = $user_info['openid'];
                $params['money'] = intval($real_price * 100);
                $params['body'] = '购买商品,订单号:' . $order_sn;
                $params['order_sn'] = $pay_sn;

                $pay_info = hook('wechat_web_pay_order', $params);

                if ($res) {
                    Db::commit();
                    $this->success('支付信息', $pay_info);
                }
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

    }

    public function pay_money()
    {
        $data = $this->request->param();
        $user_id = $this->getWechatUserId();
        $user_info = WechatUserModel::get($user_id);
        $order_sn = isset($data['order_sn']) && $data['order_sn'] ? $data['order_sn'] : '';
        $order_info = OrderInfoModel::where('order_sn', $order_sn)
            ->where('pay_status', 1)->find();
        if ((empty($order_info))) {
            $this->error('订单数据异常');
        }
        if ($order_info['card_code'] && $order_info['card_id']) {
            $card_param['company_id'] = $order_info['company_id'];
            $card_param['card_id'] = $order_info['card_id'];
            $card_param['code'] = $order_info['card_code'];
            $card_status = hook('check_card_status', $card_param);
            if ($card_status[0]['errcode'] == 0) {
                if ($card_status[0]['can_consume'] == false) {
                    throw new Exception('卡券已被使用,请重新下单');
                }
            } else {
                throw new Exception('获取卡券状态异常,请重新下单');
            }
        }
        $pay_sn = "PAY_" . cmf_get_order_sn();
        $params['company_id'] = $order_info['company_id'];
        $params['url'] = isset($data['url']) && $data['url'] ? $data['url'] : '';
        $params['openid'] = $user_info['openid'];
        $params['money'] = intval($order_info['real_price'] * 100);
        $params['body'] = '购买商品,订单号:' . $order_sn;
        $params['order_sn'] = $pay_sn;
        $order_info->pay_sn = $pay_sn;
        $order_info->save();
        $pay_info = hook('wechat_web_pay_order', $params);
        $this->success('立即支付', $pay_info);
    }

    public function delete_cart()
    {
        $data = $this->request->param();
        $user_id = $this->getWechatUserId();
        $cart_id = isset($data['cart_id']) && $data['cart_id'] ? $data['cart_id'] : '11';
        $cart_info = CartModel::where(['user_id' => $user_id])->get($cart_id);
        if (empty($cart_info)) {
            $this->error('购物车商品不存在');
        }
        $goods_info = GoodsModel::get($cart_info['goods_id']);
        $goods_info->stock = ['inc', $cart_info['num']];
        $goods_info->save();
        if ($cart_info['spec_id']) {
            $spec_info = GoodsSpecModel::get($cart_info['spec_id']);
            $spec_info->stock = ['inc', $cart_info['num']];
            $spec_info->save();
        }
        $res = $cart_info->delete();
        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }


}
